﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StevensReceipts.Domain;
using StevensReceipts.Repository;

namespace StevensReceipts.Web.Controllers
{
    public class ContactController : Controller
    {
        private readonly IReceiptsDataSource _dataSource;

        public ContactController(IReceiptsDataSource dataSource)
        {
            _dataSource = dataSource;
        }

        //
        // GET: /Contact/ display all contacts and search
        public ActionResult Index(int? businessId)
        {
            IQueryable<Contact> contacts =
                _dataSource.Contacts.Get(c => c.BusinessId == businessId || c.IsSystemContact == true);

            return View(contacts);
        }
        
        // edit an existing contact if id is not null, otherwise add a new one
        [HttpGet]
        public ActionResult Edit(int? id)
        {
            Contact contact = new Contact();
            if(id != null)
            {
                contact = _dataSource.Contacts.GetSingle(c => c.Id == id);
            }
            return View(contact);
        }



        //edit a contact
        [HttpPost]
        public ActionResult Edit(Contact contact)
        {
            _dataSource.Contacts.Update(contact);
            _dataSource.Save();
            return RedirectToAction("Index", "Contact");
        }

        //view an existing contact
        [HttpGet]
        public ActionResult Display(int id)
        {
            Contact contact = _dataSource.Contacts.GetSingle(c => c.Id == id);
            return View(contact);
        }

    }
}
